package com.alipay.rebate.shop.controller.admin;

import com.alipay.rebate.shop.core.ResultGenerator;
import com.alipay.rebate.shop.model.InviteUserSettings;
import com.alipay.rebate.shop.pojo.common.ResponseResult;
import com.alipay.rebate.shop.pojo.user.admin.InviteUserSettingsDto;
import com.alipay.rebate.shop.service.admin.InviteUserSettingsService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* Created by CodeGenerator on 2019/12/15.
*/
@RestController
@RequestMapping("/admin/invite/user/settings")
public class InviteUserSettingsController {

    private Logger logger = LoggerFactory.getLogger(InviteUserSettingsController.class);
    @Resource
    private InviteUserSettingsService inviteUserSettingsService;
    private ObjectMapper objectMapper = new ObjectMapper();

    @PutMapping("/update")
    public ResponseResult update(@RequestBody
        InviteUserSettingsDto dto) throws JsonProcessingException {

        InviteUserSettings inviteUserSettings = new InviteUserSettings();
        inviteUserSettings.setId(1);
        inviteUserSettings.setUpdateTime(new Date());
        inviteUserSettings.setRuleHtml(dto.getRuleHtml());
        if(dto.getImgs() != null){
            String imgJson = objectMapper.writeValueAsString(dto.getImgs());
            inviteUserSettings.setImgs(imgJson);
        }
        inviteUserSettingsService.update(inviteUserSettings);
        return ResultGenerator.genSuccessResponseResult();
    }

    @GetMapping("/detail")
    public ResponseResult detail() throws Exception{
        InviteUserSettings inviteUserSettings = inviteUserSettingsService.findById(1);
        logger.debug("InviteUserSettings is : {}",inviteUserSettings);
        InviteUserSettingsDto dto = new InviteUserSettingsDto();
        dto.setRuleHtml(inviteUserSettings.getRuleHtml());
        List<String> img = objectMapper.readValue(inviteUserSettings.getImgs(),
            new TypeReference<List<String>>(){});
        dto.setImgs(img);
        return ResultGenerator.genSuccessResponseResult(dto);
    }

}
